import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:sph_driver/AppConfig/LocalStorage.dart';

import '../../AppConfig/Config.dart';
import '../../AppConfig/RouteAct.dart';
import '../../Main/MyWallet/PayAuthentication.dart';
import '../../TabBar/TabbarView.dart';
import '../../http/NoLoadingGetApi.dart';
import '../../http/NoLoadingPostApi.dart';
import '../../http/api.dart';
import 'FreightPaymentSuccessful.dart';

class PayTheDeposit extends StatefulWidget {
  const PayTheDeposit({super.key, required this.dataMap});
  final Map dataMap;
  @override
  State<PayTheDeposit> createState() => _PayTheDepositState();
}

class _PayTheDepositState extends State<PayTheDeposit> {
  int payType=-1;
  bool walletType=false;
  String phoneNum="";
  String userMoney="";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getUserInfo();
  }
  void getUserInfo()async{
    phoneNum=(await PhoneNumManager.getPhone())!;
    NoLoadinggetApiManager.getData(
      context, // 上下文对象，用于显示提示信息等
      'api/pay/driver/user/balanceInfo', // 您的API端点
      {}, // 查询参数，如果没有可以传递null
          (responseData)  {
        setState(() {
            userMoney=responseData['data']['balance'].toString();
            if(responseData['data']['passwordStatus']!=null&&responseData['data']['passwordStatus']==1){
              walletType=true;
            }else{
              walletType=false;
            }
        });
      },
    );
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        title:Text( "结算",style: TextStyle(fontWeight: FontWeight.w300,fontSize: 16.sp),),
        backgroundColor: Colors.white,
        leading: IconButton(
          onPressed: () {
            if(widget.dataMap['isDriverAdd']) {
              if (widget.dataMap['isCaptain'] == 1) {
                NoLoadingApiManager.postData(
                  context,
                  'api/pay/driver/user/cancelPayDepositByCaptain',
                  {
                    "serialNum": widget.dataMap['serialNum'],
                  },
                      (responseData) {
                    Navigator.pop(context);
                  },
                );
              } else {
                NoLoadingApiManager.postData(
                  context,
                  'api/pay/driver/user/cancelPayDepositByDriver',
                  {
                    "serialNum": widget.dataMap['serialNum'],
                  },
                      (responseData) {
                    Navigator.pop(context);
                  },
                );
              }
            }else{
              NoLoadingApiManager.postData(
                context,
                'api/pay/driver/user/cancelPayDepositByShipper',
                {
                  "serialNum": widget.dataMap['serialNum'],
                },
                    (responseData) {
                  Navigator.pop(context);
                },
              );
            }
          },
          icon: Icon(Icons.arrow_back_ios),
        ),
        centerTitle: true,
      ),
      body:Column(
        children: [
          Expanded(child: ListView(
            children: [
              Container(
                margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                padding: EdgeInsets.only(top: 22.h,bottom: 23.h),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Column(
                          children: [
                            Text("费用 ¥",style: TextStyle(color: Color.fromRGBO(228, 28, 35, 1),fontWeight: FontWeight.w600,fontSize: 14.sp),),
                            SizedBox(height: 2.h,),
                          ],
                        ),
                        Text(widget.dataMap['payTotal'],style: TextStyle(color: Color.fromRGBO(228, 28, 35, 1),fontSize: 20.sp,fontWeight: FontWeight.w600),),
                      ],
                    ),

                    Container(
                      padding: EdgeInsets.all(10.h),
                      margin: EdgeInsets.only(top: 14.h),
                      width: screenSize.width-20.w,
                      height: 40.h,
                      color: Color.fromRGBO(251, 241, 233, 1),
                      child: Text("请选择支付方式",style: TextStyle(color: MyColors.themeColor,fontSize: 16.sp),),
                    ),
                    SizedBox(height: 10.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            SizedBox(width: 10.w,),
                            Image.asset("lib/Images/OrderList/余额支付.png",width: 30.w,height: 30.h,),
                            SizedBox(width: 6.w,),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text("余额支付",style: TextStyle(color: Colors.black,),),
                                Text("可用"+userMoney+"元",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                              ],
                            ),

                          ],
                        ),
                        IconButton(onPressed: (){
                          setState(() {
                            payType=1;
                          });
                        }, icon:payType==1?Icon(Icons.check_circle,color: MyColors.themeColor,):Icon(Icons.panorama_fish_eye,color: MyColors.authTipColor,) ),
                      ],
                    ),
                    Divider(height: 20.h,color: MyColors.backgreyColor,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            SizedBox(width: 10.w,),
                            Image.asset("lib/Images/OrderList/微信支付.png",width: 30.w,height: 30.h,),
                            SizedBox(width: 6.w,),
                            Text("微信支付",style: TextStyle(color: Colors.black,),),
                          ],
                        ),
                        IconButton(onPressed: (){
                          setState(() {
                            payType=2;
                          });
                        }, icon:payType==2?Icon(Icons.check_circle,color: MyColors.themeColor,):Icon(Icons.panorama_fish_eye,color: MyColors.authTipColor,) ),
                      ],
                    ),
                    Divider(height: 20.h,color: MyColors.backgreyColor,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            SizedBox(width: 10.w,),
                            Image.asset("lib/Images/OrderList/支付宝支付.png",width: 30.w,height: 30.h,),
                            SizedBox(width: 6.w,),
                            Text("支付宝支付",style: TextStyle(color: Colors.black,),),
                          ],
                        ),
                        IconButton(onPressed: (){
                          setState(() {
                            payType=3;
                          });
                        }, icon:payType==3?Icon(Icons.check_circle,color: MyColors.themeColor,):Icon(Icons.panorama_fish_eye,color: MyColors.authTipColor,) ),
                      ],
                    ),
                    Divider(height: 20.h,color: MyColors.backgreyColor,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            SizedBox(width: 10.w,),
                            Image.asset("lib/Images/OrderList/银行卡支付.png",width: 30.w,height: 30.h,),
                            SizedBox(width: 6.w,),
                            Text("招商银行储蓄卡(9999)",style: TextStyle(color: Colors.black,),),
                          ],
                        ),
                        Row(
                          children: [
                            BrnTagCustom.buildBorderTag(
                              tagText: '支付立减6.9元',
                              textColor:Color.fromRGBO(246, 57, 13, 1),
                              borderColor: Color.fromRGBO(246, 57, 13, 1),
                              borderWidth: 1,
                              fontSize: 12.sp,
                            ),
                            IconButton(onPressed: (){
                              setState(() {
                                payType=4;
                              });

                            }, icon:payType==4?Icon(Icons.check_circle,color: MyColors.themeColor,): Icon(Icons.panorama_fish_eye,color: MyColors.authTipColor,) ),
                          ],
                        ),
                      ],
                    ),
                    Divider(height: 20.h,color: MyColors.backgreyColor,),
                    GestureDetector(
                      child:  Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text("    "+"其他付款方式",style: TextStyle(color: Colors.black),),
                          Row(
                            children: [
                              Text("其他付款方式",style: TextStyle(color:MyColors.authTipColor),),
                              Icon(Icons.arrow_forward_ios,color: MyColors.authTipColor,size: 14,),
                              SizedBox(width: 10.w,),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),

            ],
          ),
          ),
          Container(
            color: Colors.white,
            width: screenSize.width,
            height: 85.h,
            padding: EdgeInsets.only(top: 10.h,right: 15.w,left: 15.w,bottom: 40.h),
            child:BrnSmallMainButton(
              title: '立即支付¥'+widget.dataMap['payTotal'],
              textColor: Colors.white,
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              bgColor: MyColors.themeColor,
              radius: 30,
              onTap: () {
                if(payType==-1){
                  BrnToast.show("请选择支付方式", context, duration: BrnDuration.short,);
                }else if(payType==1){
                  if(walletType){
                    showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return EnterPasswordForDeposit(dataMap: widget.dataMap, phoneNum: phoneNum,);
                      },
                    );
                  }else{
                    showDialog(
                      barrierDismissible: false,
                      context: context,
                      builder: (BuildContext context) {
                        return BrnDialog(
                          titleText: "温馨提示",
                          messageText: "您尚未设置支付密码，请前往设置。",
                          actionsWidget: [
                            TextButton(
                              onPressed: () {
                                Navigator.pop(context);
                              },
                              child: Text("我再想想",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                            ),
                            TextButton(
                              onPressed: () async{
                                Navigator.pop(context);
                              final result=await  Navigator.push( context, FadeRoute(page:PayAuthentication(phoneNum: phoneNum,)));
                                if(result!=null){
                                  getUserInfo();
                                }
                              },
                              child: Text("现在就去",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                            ),
                          ],
                        );
                      },
                    );
                  }
                //
                }


              },
            ),
          )
        ],
      ) ,
    );
  }
}
class EnterPasswordForDeposit extends StatefulWidget {
  const EnterPasswordForDeposit({super.key, required this.dataMap, required this.phoneNum});
  final Map dataMap;
  final String phoneNum;
  @override
  State<EnterPasswordForDeposit> createState() => _EnterPasswordForDepositState();
}

class _EnterPasswordForDepositState extends State<EnterPasswordForDeposit> {
  TextEditingController _controller = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: Container(
        padding: EdgeInsets.all(16),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10))),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(),
                IconButton(
                  icon: Icon(Icons.close,color: Colors.black,),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                ),
              ],
            ),

            Text(
              '请输入支付密码',
              style: TextStyle(
                color:MyColors.textColor,
                fontSize: 16.sp,
              ),
            ),
            SizedBox(height: 16),
            Container(
              // margin: EdgeInsets.only(left: 10.w,right:10.w),
              child: PinCodeTextField(
                  obscureText:true,
                  appContext: context,//context
                  length: 6,//输入的长度
                  controller: _controller,
                  autoFocus: true,
                  keyboardType: TextInputType.number,
                  textStyle:TextStyle(color: Colors.black),
                  cursorColor: Colors.black,
                  pinTheme: PinTheme(
                    shape: PinCodeFieldShape.box, //输入框的形状
                    borderRadius: const BorderRadius.all(Radius.circular(0)),
                    activeColor:MyColors.themeColor,
                    selectedColor:MyColors.authTipColor,
                    inactiveColor:MyColors.backgreyColor,

                  ),

                  onChanged: (value)  async {

                    if(value.length==6) {

                      if(widget.dataMap['isCaptain']==1){
                        ApiManager.postData(
                          context,
                          'api/pay/driver/user/doPayDepositByCaptain',
                          {
                            "serialNum": widget.dataMap['serialNum'],
                            "channel": "WALLET",
                            "password": value,
                            "authEtc": widget.dataMap['authEtc'],
                            "vehicleId": widget.dataMap['vehicleId'],
                          },
                              (responseData)  {
                            Navigator.pop(context);
                            Navigator.push( context, FadeRoute(page:FreightPaymentSuccessful(dataMap: widget.dataMap,
                            )));
                          },
                        );
                      }else{
                      if(widget.dataMap['isDriverAdd']){
                        ApiManager.postData(
                          context,
                          'api/pay/driver/user/doPayDepositByDriver',
                          {
                            "serialNum": widget.dataMap['serialNum'],
                            "channel": "WALLET",
                            "password": value,
                            "authEtc": widget.dataMap['authEtc']
                          },
                              (responseData)  {
                            Navigator.push( context, FadeRoute(page:FreightPaymentSuccessful(dataMap: widget.dataMap,
                            )));
                          },
                        );
                      }else{
                        ApiManager.postData(
                          context,
                          'api/pay/driver/user/doPayDepositByShipper',
                          {
                            "waybillId":widget.dataMap['waybillId'],
                            "serialNum": widget.dataMap['serialNum'],
                            "channel": "WALLET",
                            "password": value,
                            "authEtc": widget.dataMap['authEtc']
                          },
                              (responseData)  {
                                Navigator.pushReplacement(
                                  context,
                                  MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 2,),fullscreenDialog: true,),
                                );
                          },
                        );
                      }

                      }
                    }

                  }
              ),
            ),

            SizedBox(height: 16),
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                Navigator.push( context, FadeRoute(page:PayAuthentication(phoneNum:widget.phoneNum,)));

              },
              child: Text('忘记密码？',
                style: TextStyle(
                  color: MyColors.themeColor,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
